package top.lywivan.utils;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/*
    读取beans.properties配置文件
    创建接口实现类对象的工具类
 */
public class BeanFactory {
    //创建Map集合对象,存储的是配置文件中配置的接口和实现类对象
    private static Map<String,Object> map = new HashMap<>();
    //静态代码块
    static {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("beans");
        Enumeration<String> keys = resourceBundle.getKeys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            String className = resourceBundle.getString(key);
            try {
                Class<?> clazz = Class.forName(className);
                Object obj = clazz.newInstance();
                map.put(key, obj);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    //根据接口Class对象,获取实现类对象
    public static <T> T getBean(Class<T> clazz) {
        //获取接口名称(不包含包名)
        String interfaceName = clazz.getSimpleName();
        return (T)map.get(interfaceName);
    }
}
